<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17
 * Time: 15:38
 * 后台角色管理
 */

namespace app\admin\controller;

use app\admin\Base;
use app\admin\model\Menus;
use app\admin\model\Roles;
use think\Db;
use think\Loader;

class Role extends Base
{
    public function index()
    {
        $name = $this->request->param('name', '');
        $status = $this->request->param('status', '');
        $where = [];
        if(!empty($name)){
            $where['name']  = ['like',"%$name%"];
        }
        if($status != ''){
            $where['status'] = $status;
        }
        $model = new Roles();
        $count = $model->where($where)->count();

        $list = $model->field('*')->order('create_time desc')->where($where)->paginate(20);

        $page = $list->render();

        return $this->fetch('',compact('count', 'list', 'page'));
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\RoleValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            //写入数据
            $model = new Roles();
            $model->name = $data['name'];
            $model->remark = $data['remark'] ?? '';
            $model->status = $data['status'];
            $model->create_time = time();
            $model->update_time = time();
            $model->update_by = parent::$uid;
            $rs = $model->save();
            if(!$rs){
                return ajax_return_adv_error("添加失败");
            }else{
                return ajax_return_adv('添加成功');
            }
        } else {
            // 添加页面
            return $this->fetch();
        }
    }

    public function edit()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            // 验证
            $validate = validate('app\admin\validate\RoleValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            //保存数据
            $model = new Roles();
            $data['update_time'] = time();
            $data['update_by'] = parent::$uid;
            $rs = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            if(!$rs){
                return ajax_return_adv_error("编辑失败");
            }else{
                return ajax_return_adv('编辑成功');
            }
        } else {
            // 编辑页面
            $id = $this->request->param('id',0);
            if(empty($id)){
                return ajax_return_adv_error("角色id不能为空");
            }
            $model = new Roles();
            $info = $model->get($id);

            return $this->fetch('', ['info' => $info]);
        }
    }

    public function delete()
    {
        $model = new Roles();
        $id = $this->request->param('id',0);
        if(empty($id)){
            return ajax_return_adv_error("角色id不能为空");
        }
        Db::startTrans();
        try{
            //先删除角色表
            Db::name('roles')->where('id', $id)->delete();
            //角色-菜单关系表先删除再添加记录
            Db::name('role_menus')->where('role_id', $id)->delete();
            //先确认角色是否关联管理员
            $operatorids = Db::name('role_operators')->where('role_id', $id)->column('operator_id');
            if(!empty($operatorids)){
                //如果存在关联管理员，先删除关联关系
                Db::name('role_operators')->where('role_id', $id)->delete();
                //最后把redis缓存存在的管理员权限重新赋值
                $this->delRoleAndRedis($operatorids);
            }
            // 提交事务
            Db::commit();
            return ajax_return_adv("删除成功");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_adv_error("删除失败");
        }
    }

    /**
     * @todo 授权
    */
    public function addMenu()
    {
        $role_id = $this->request->param('id/d');
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (!$role_id) {
                return ajax_return_adv_error("缺少必要参数");
            }
            // 验证
            $validate = validate('app\admin\validate\RoleMenusValidate');
            if (!$validate->check($data)) {
                return ajax_return_adv_error($validate->getError());
            }
            foreach($data['menu_ids'] as $key=>$value){
                //去空
                if(empty($value)){
                    unset($data['menu_ids'][$key]);
                }
            }
            //验证菜单是否存在
            $model = new Menus();
            if($data['menu_ids']){
                $rs = $model->validateMenus($data['menu_ids']);
                if(!$rs){
                    return ajax_return_adv_error("所选菜单不存在，请核查");
                }
            }
            Db::startTrans();
            try{
                //角色-菜单关系表先删除再添加记录
                Db::name('role_menus')->where('role_id', $role_id)->delete();
                foreach($data['menu_ids'] as $k=>$v){
                    $list[$k]['role_id'] = $role_id;
                    $list[$k]['menu_id'] = $v;
                }
                Db::name('role_menus')->insertAll($list);
                // 提交事务
                Db::commit();
                return ajax_return_adv("权限分配成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error("权限分配失败");
            }
        } else {
            //获取角色信息
            if(empty($role_id)){
                return ajax_return_adv_error("角色id不能为空");
            }
            $model = new Roles();
            $info = $model->get($role_id);

            $tree = Loader::model('Menu', 'logic')->getTree($role_id);
            $tree = json_encode($tree);

            return $this->fetch('',compact('info', 'roles', 'tree'));
        }
    }
}